package com.mmd.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.mmd.common.PullLogisticsUtils;
import com.mmd.common.bean.KDniaoLogisticsResult;
import com.mmd.common.entity.MmdOrder;
import com.mmd.common.entity.MmdOrderLogistics;
import com.mmd.common.enums.LogisticsStatusEnums;
import com.mmd.common.enums.StatusEnums;
import com.mmd.manage.dao.MmdOrderDao;
import com.mmd.manage.dao.MmdOrderLogisticsDao;
import com.mmd.manage.service.PullLogisticsInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;

@Service
public class PullLogisticsInfoServiceImpl implements PullLogisticsInfoService {


	@Autowired
	private MmdOrderDao mmdOrderDao;
	@Autowired
	private MmdOrderLogisticsDao mmdOrderLogisticsDao;
	@Value("${kdniao.apikey}")
	private String appkey;
	@Value("${kdniao.userid}")
	private String userid;

	@Override
	@Transactional
	public void pull(MmdOrder order) {
		KDniaoLogisticsResult kDniaoLogisticsResult = PullLogisticsUtils.pullLogisticsInfoBy17Track(order);
		if (kDniaoLogisticsResult != null && !CollectionUtils.isEmpty(kDniaoLogisticsResult.getTraces())) {
			MmdOrderLogistics logistics1 = mmdOrderLogisticsDao.selectByPrimaryKey(order.getOrderNo());
			MmdOrderLogistics logistics = new MmdOrderLogistics();
			logistics.setOrderNo(order.getOrderNo());
			logistics.setLogistics(JSON.toJSONString(kDniaoLogisticsResult.getTraces()));
			logistics.setUpdateTime(new Date());
			if (logistics1 != null) {
				mmdOrderLogisticsDao.updateByPrimaryKeySelective(logistics);
			}else{
				logistics.setLogisticsCompanyCode(order.getLogisticsCompanyCode());
				logistics.setLogisticsCompanyName(order.getLogisticsCompanyName());
				logistics.setLogisticsNo(order.getLogisticsNo());
				logistics.setCreateTime(new Date());
				mmdOrderLogisticsDao.insert(logistics);
			}

			if (LogisticsStatusEnums.sign_complete.getCode().equals(kDniaoLogisticsResult.getState())) {
				MmdOrder order1 = new MmdOrder();
				order1.setOrderNo(order.getOrderNo());
				order1.setStatus(StatusEnums.SIGN.getCode());
				mmdOrderDao.updateByPrimaryKeySelective(order1);
			}
		}
	}
}
